<?php

class ConfigController extends AdminController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	public function actionIndex()
	{
		$model=$this->loadModel(1);
                    
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
                $dir = Yii::getPathOfAlias('application.uploads.images');
		if(isset($_POST['Config']))
		{
                    $model->attributes=$_POST['Config'];
                    $model->bannerfile = CUploadedFile::getInstance($model, 'bannerfile');
                    $model->logofile = CUploadedFile::getInstance($model, 'logofile');
                    if (isset($model->bannerfile) && $model->validate(array('bannerfile'))) {
                        $filename = $model->bannerfile->getName();
                        //convert string to lowercase
                        $filename = trim($filename, '-');
                        //trim whitespaces
                        $uploaded = $model->bannerfile->saveAs($dir . '/' . $filename);
                        $model->banner = $filename;
                        //Load image to resize
                        $image = new SimpleImage();
                        $image->load($dir . '/' . $filename);
                        $image->resize(330,106);
                        $image->save($dir . '/' . $filename);
                    }
                    if (isset($model->logofile) && $model->validate(array('logofile'))) {
                        $filename = $model->logofile->getName();
                        //convert string to lowercase
                        $filename = trim($filename, '-');
                        //trim whitespaces
                        $uploaded = $model->logofile->saveAs($dir . '/' . $filename);
                        $model->logo = $filename;
                        
                    }
                    if($model->save())
				Yii::app()->user->setFlash('config', 'The content is updated successfully!');
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Config the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Config::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Config $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='config-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
